package com.gzbugu.polytechsasia.service.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import com.gzbugu.polytechsasia.dao.DatabaseLinkDAO;
import com.gzbugu.polytechsasia.factory.DAOFactory;
import com.gzbugu.polytechsasia.service.IDeleteArticleService;
import com.gzbugu.polytechsasia.vo.Article;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created with IntelliJ IDEA. User: Bokchoy Date: 11/1/12 Time: 11:27 AM
 */
public class DeleteArticleService implements IDeleteArticleService {

	private static Logger log = LoggerFactory
			.getLogger(DeleteArticleService.class);

	public boolean deleteArticleById(int id) {
		log.debug("delete article by id: " + id);
		try {
			Article instance = DAOFactory.getArticleDAO().findById(id);
			DAOFactory.getArticleDAO().delete(instance);
            return true;
		} catch (Exception e) {
			log.error(e.toString());
		}
		return false;
	}

	public int deleteArticleByIds(String ids) {
		log.debug("delete article by ids:" + ids);
		if (!isIdsValidate(ids)) {
			log.error("ids is not validate and return 0");
			return 0;
		}
		String sql = "DELETE FROM Article WHERE id IN (" + ids + ")";
		Connection connection = DatabaseLinkDAO.getConnection();
		try {
			Statement statement = connection.createStatement();
			int result = statement.executeUpdate(sql);
			log.debug("delete successful!");
			return result;
		} catch (SQLException e) {
			log.error("delete failed and return 0,sql:" + sql, e);
			return 0;
		}
	}

	private boolean isIdsValidate(String ids) {
		String[] idsArray = ids.split(",");
		for (String id : idsArray) {
			if (!id.matches("[0-9]+"))
				return false;
		}
		return true;
	}

	public boolean deleteArticlesById(int id[]) {
		boolean flag = true;
		for (int i : id) {
			if (!deleteArticleById(i)) {
				flag = false;
			}
		}
		return flag;
	}

}
